﻿using System;
using System.Collections.Generic;
using System.Text;

namespace TomNet.Attributes
{
    /// <summary>
    /// 字符串长度范围检测
    /// </summary>
    public class StringRangeAttribute : BaseAttribute
    {
        public int Min { get; set; }
        public int Max { get; set; }
        public override string Error
        {
            get
            {
                if (base.Error != null)
                {
                    return base.Error;
                }
                return $"字符串长度范围{Min}-{Max}";
            }
            set => base.Error = value;
        }
        public override bool Validate(object value)
        {
            var result = true;
            if (value != null)
            {
                if (value is IList<string> list)
                {
                    foreach (var item in list)
                    {
                        if (!(item.ToString().Length >= Min && item.ToString().Length <= Max))
                        {
                            result = false;
                            break;
                        }
                    }
                }
                else
                {
                    result = value.ToString().Length >= Min && value.ToString().Length <= Max;
                }
            }
            return result;
        }
    }
}
